package models

import (
	"errors"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// 团购状态常量
const (
	GroupStatusPending int8 = 1 // 待成团
	GroupStatusSuccess int8 = 2 // 已成团
	GroupStatusFailed  int8 = 3 // 未成团
)

// GroupBuyOrder 团购订单模型
type GroupBuyOrder struct {
	BaseModel
	OrderNo      string `orm:"size(32);unique" json:"order_no"`    // 订单号
	OrderId      int64  `orm:"default(0)" json:"order_id"`         // 使用的订单ID
	Type         string `orm:"size(20);default(self)" json:"type"` // 订单类型: self, meituan, douyin
	ActivityId   int64  `orm:"index" json:"activity_id"`           // 团购活动ID
	ActivityName string `orm:"size(100)" json:"activity_name"`     // 团购活动名称
	UserId       int64  `orm:"index" json:"user_id"`               // 用户ID
	MemberId     int64  `orm:"index" json:"member_id"`             // 会员ID
	Username     string `orm:"size(50)" json:"username"`           // 用户名
	Phone        string `orm:"size(20)" json:"phone"`              // 联系电话
	Quantity     int    `orm:"default(1)" json:"quantity"`         // 购买数量
	Amount       int64  `orm:"default(0)" json:"amount"`           // 订单金额(分)
	Status       int8   `orm:"default(1)" json:"status"`           // 订单状态
	GroupStatus  int8   `orm:"default(1)" json:"group_status"`     // 团购状态
	Address      string `orm:"size(255)" json:"address"`           // 收货地址
	Remark       string `orm:"size(500)" json:"remark"`            // 备注
	PaidAt       int64  `orm:"default(0)" json:"paid_at"`          // 支付时间
}

// TableName 设置表名
func (g *GroupBuyOrder) TableName() string {
	return "ss_group_buy_order"
}

// GetGroupBuyOrderById 根据ID获取团购订单
func GetGroupBuyOrderById(id int64) (*GroupBuyOrder, error) {
	o := orm.NewOrm()
	order := &GroupBuyOrder{BaseModel: BaseModel{Id: id}}
	err := o.Read(order)
	return order, err
}

// GetGroupBuyOrderList 获取团购订单列表
func GetGroupBuyOrderList(page, pageSize int, filters map[string]interface{}) ([]*GroupBuyOrder, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(GroupBuyOrder))

	// 应用过滤条件
	if orderNo, ok := filters["order_no"].(string); ok && orderNo != "" {
		qs = qs.Filter("order_no__contains", orderNo)
	}
	if activityName, ok := filters["activity_name"].(string); ok && activityName != "" {
		qs = qs.Filter("activity_name__contains", activityName)
	}
	if username, ok := filters["username"].(string); ok && username != "" {
		qs = qs.Filter("username__contains", username)
	}
	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}
	if groupStatus, ok := filters["group_status"].(int8); ok {
		qs = qs.Filter("group_status", groupStatus)
	}
	if startTime, ok := filters["start_time"].(int64); ok {
		qs = qs.Filter("created_at__gte", startTime)
	}
	if endTime, ok := filters["end_time"].(int64); ok {
		qs = qs.Filter("created_at__lte", endTime)
	}

	// 添加加盟商过滤条件
	if franchiseIds, ok := filters["franchise_ids"].([]int64); ok && len(franchiseIds) > 0 {
		qs = qs.Filter("franchise_id__in", franchiseIds)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var orders []*GroupBuyOrder
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&orders)

	return orders, total, err
}

// UpdateGroupBuyOrder 更新团购订单
func UpdateGroupBuyOrder(order *GroupBuyOrder) error {
	o := orm.NewOrm()
	_, err := o.Update(order, "Status", "GroupStatus", "Remark", "UpdatedAt", "UpdatedBy")
	return err
}

// AuditGroupBuyOrder 审核团购订单
func AuditGroupBuyOrder(id int64, status int8, remark string, operator string) error {
	o := orm.NewOrm()
	order := &GroupBuyOrder{BaseModel: BaseModel{Id: id}}
	if err := o.Read(order); err != nil {
		return err
	}

	// 检查订单状态
	if order.Status != OrderStatusPending {
		return errors.New("订单状态不正确，无法审核")
	}

	// 更新订单状态
	order.Status = status
	order.Remark = remark
	order.UpdatedBy = operator
	order.UpdatedAt = time.Now().Unix()

	_, err := o.Update(order, "Status", "Remark", "UpdatedAt", "UpdatedBy")
	return err
}

// CancelGroupBuyOrder 取消团购订单
func CancelGroupBuyOrder(id int64, operator string) error {
	o := orm.NewOrm()
	order := &GroupBuyOrder{BaseModel: BaseModel{Id: id}}
	if err := o.Read(order); err != nil {
		return err
	}

	// 检查订单状态
	if order.Status != GroupBuyOrderStatusApproved {
		return errors.New("订单状态不正确，无法取消")
	}

	// 更新订单状态
	order.Status = OrderStatusCanceled
	order.UpdatedBy = operator
	order.UpdatedAt = time.Now().Unix()

	_, err := o.Update(order, "Status", "UpdatedAt", "UpdatedBy")
	return err
}

// CreateGroupBuyOrder 创建团购订单
func CreateGroupBuyOrder(order *GroupBuyOrder) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(order)
	return id, err
}

// GetMemberGroupBuyPurchasedCount 获取会员已购买指定团购活动的数量
func GetMemberGroupBuyPurchasedCount(memberId, activityId int64) (int, error) {
	o := orm.NewOrm()
	var count int

	// 统计已支付的订单中的数量总和
	err := o.Raw("SELECT IFNULL(SUM(quantity), 0) FROM ss_group_buy_order WHERE user_id = ? AND activity_id = ? AND status IN (2, 3) AND is_deleted = 0", memberId, activityId).QueryRow(&count)

	return count, err
}

// UseGroupBuyTx 在事务中使用团购券
func UseGroupBuyTx(tx orm.TxOrmer, groupBuyId int64, userId int64, orderId int64) error {
	// 获取团购券信息
	groupBuy := &GroupBuyOrder{BaseModel: BaseModel{Id: groupBuyId}}
	err := tx.Read(groupBuy)
	if err != nil {
		return err
	}

	// 检查团购券是否属于当前用户
	if groupBuy.UserId != userId {
		return errors.New("团购券不属于当前用户")
	}

	// 检查团购券状态
	if groupBuy.Status != GroupBuyOrderStatusPaid {
		return errors.New("团购券状态异常")
	}

	// 更新团购券状态为已使用
	groupBuy.Status = GroupBuyOrderStatusCompleted
	groupBuy.UpdatedAt = time.Now().Unix()
	groupBuy.OrderId = orderId
	_, err = tx.Update(groupBuy)
	return err
}
